package com.peanut.baby.http;

import com.peanut.baby.InitManager;
import com.tencent.mars.xlog.Log;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created by anonymouslystudio on 2017/6/15.
 */

public abstract  class BaseObserver<T> implements Observer<BaseResponse<T>> {
    private static final String TAG = "BaseObserver";

    protected BaseObserver() {

    }

    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(BaseResponse<T> value) {
        try {
            if (value.code.equals(BaseResponse.CODE_SUCCESS)) {
                T t = value.data;
                onHandleSuccess(t);
            } else {
                onHandleError(value.code,value.error);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "Exception "+e.toString());
            onHandleError(value.code,e.toString());
        }
    }

    @Override
    public void onError(Throwable e) {
        Log.e(TAG, "error:" + e.toString());
        if(e instanceof ApiException){
            ApiException exception = (ApiException) e;
            Log.e(TAG, "ApiException:" + exception.mErrorCode);
            if (exception.isTokenExpried()) {
                InitManager.getInstance().onApiError(ApiException.ERROR_TOKEN_EXPRIED);
            }else if(exception.isLackOfPoint()) {
                InitManager.getInstance().onApiError(ApiException.ERROR_LACK_OF_POINT);
            }else if(exception.isNeedToken()) {
                InitManager.getInstance().onApiError(ApiException.ERROR_NEED_TOKEN);
            }
            onHandleError(exception.mErrorCode,exception.getMessage());
            return;
        }

         onHandleError("-1","请检查网络连接");



    }

    @Override
    public void onComplete() {
    }

    protected abstract void onHandleSuccess(T t);

    protected abstract void onHandleError(String code,String msg);

}
